import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_todo/models/auth_token/auth_token.model.dart';
import 'package:flutter_todo/models/todo/todo.model.dart';

/// 单例模式的应用请求类
class AppRequest {
  /// 网络请求
  static Dio _http = Dio(BaseOptions(
      baseUrl: 'http://todo.dloa.xyz:5000/api/',
      contentType: 'application/json'));

  /// 实现饿汉式单例模式
  static AppRequest _instance = AppRequest._internal();
  factory AppRequest() => _instance;
  AppRequest._internal();

  /// 登录
  Future<AuthTokenModel> login(String account, String password) async {
    Response res = await _http.get('auth/token',
        options: Options(headers: {
          'account': account,
          'password': password,
        }));

    AuthTokenModel authTokenModel = AuthTokenModel.fromJson(res.data);
    _http.options.headers[HttpHeaders.authorizationHeader] =
        'Bearer ${authTokenModel.token}';

    return authTokenModel;
  }

  /// 获取所有待办事项
  Future<List<TodoModel>> getAllTodo() async {
    Response res = await _http.get('todos');

    return getTodoModelList(res.data);
  }
}
